
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Swoole仿workerman-chat PHP聊天室 Websocket(HTLM5/Flash)+PHP多进程socket实时推送技术</title>
<script type="text/javascript">
  //WebSocket = null;
  </script>
<link href="/Public/Swoole/css/bootstrap.min.css" rel="stylesheet">
<link href="/Public/Swoole/css/style.css" rel="stylesheet">
<!-- Include these three JS files: -->
<script type="text/javascript" src="/Public/Swoole/js/swfobject.js"></script>
<script type="text/javascript" src="/Public/Swoole/js/web_socket.js"></script>
<script type="text/javascript" src="/Public/Swoole/js/jquery.min.js"></script>
<script type="text/javascript">
    if (typeof console == "undefined") {    this.console = { log: function (msg) {  } };}
    WEB_SOCKET_SWF_LOCATION = "/swf/WebSocketMain.swf";
    WEB_SOCKET_DEBUG = true;
    var ws, name, client_id, client_list={};

    // 连接服务端
    function connect() {
       // 创建websocket
       ws = new WebSocket("ws://139.129.31.227:9502");
       // 当socket连接打开时，输入用户名
       ws.onopen = onopen;
       // 当有消息时根据消息类型显示不同信息
       ws.onmessage = onmessage; 
       ws.onclose = function() {
          console.log("连接关闭，定时重连");
          connect();
       };
       ws.onerror = function() {
          console.log("出现错误");
       };
    }

    // 连接建立时发送登录信息
    function onopen()
    {
        if(!name)
        {
            show_prompt();
        }
        // 登录
        var login_data = '{"type":"login","client_name":"'+name.replace(/"/g, '\\"')+'","room_id":"1"}';
        console.log("websocket握手成功，发送登录数据:"+login_data);
        ws.send(login_data);
    }

    // 服务端发来消息时
    function onmessage(e)
    {
        console.log(e.data);
        var data = eval("("+e.data+")");
        switch(data['type']){
            // 服务端ping客户端
            case 'ping':
                ws.send('{"type":"pong"}');
                break;;
            // 登录 更新用户列表
            case 'login':
                //{"type":"login","client_id":xxx,"client_name":"xxx","client_list":"[...]","time":"xxx"}
                if(data['client_list'])
                {
                    //纪录客户端号
                    if(!client_id)
                        client_id = data['client_id'];
                    client_list = data['client_list'];
                }
                else
                {
                    client_list[data['client_id']] = {'client_id':data['client_id'], 'client_name':data['client_name']}; 
                    say(data['client_id'], data['client_name'],  data['client_name']+' 加入了聊天室', data['time']);
                }
                flush_client_list();
                console.log(data['client_name']+"登录成功");
                break;
            // 发言
            case 'say':
                //{"type":"say","from_client_id":xxx,"to_client_id":"all/client_id","content":"xxx","time":"xxx"}
                say(data['from_client_id'], data['from_client_name'], data['content'], data['time']);
                break;
            // 用户退出 更新用户列表
            case 'logout':
                //{"type":"logout","client_id":xxx,"time":"xxx"}
                say(data['from_client_id'], data['from_client_name'], data['from_client_name']+' 退出了', data['time']);
                delete client_list[data['from_client_id']];
                flush_client_list();
        }
    }

    // 输入姓名
    function show_prompt(){  
        name = prompt('输入你的名字：', '');
        if(!name || name=='null'){  
            alert("输入名字为空或者为'null'，请重新输入！");  
            show_prompt();
        }
    }  

    // 提交对话
    function onSubmit() {
      var input = document.getElementById("textarea");
      var to_client_id = $("#client_list option:selected").attr("value");
      var to_client_name = $("#client_list option:selected").text();
      ws.send('{"type":"say","to_client_id":"'+to_client_id+'","to_client_name":"'+to_client_name+'","content":"'+input.value.replace(/"/g, '\\"').replace(/\n/g,'\\n').replace(/\r/g, '\\r')+'"}');
      input.value = "";
      input.focus();
    }
    // 提交竞猜
    function onGuess() {
      var input = document.getElementById("input_guess").value;
	  if(isNaN(input)){
		alert("请输入1-100之间的数字");return;
	  }
      ws.send('{"type":"guessing","content":"'+input+'"}');
      input.value = "";
      input.focus();
    }

    // 刷新用户列表框
    function flush_client_list(){
        var userlist_window = $("#userlist");
        var client_list_slelect = $("#client_list");
        userlist_window.empty();
        client_list_slelect.empty();
        userlist_window.append('<h4>在线用户</h4><ul>');
        client_list_slelect.append('<option value="all" id="cli_all">所有人</option>');
        for(var p in client_list){
            if(p != client_id){
                client_list_slelect.append('<option value="'+p+'">'+client_list[p]['client_name']+'</option>');
                userlist_window.append('<li id="'+p+'">'+client_list[p]['client_name']+'</li>');
            }else{
                userlist_window.append('<li id="'+p+'" style="color:red">'+client_list[p]['client_name']+'</li>');
            }
                
        }
        $("#client_list").val(select_client_id);
        userlist_window.append('</ul>');
    }

    // 发言
    function say(from_client_id, from_client_name, content, time){
        if(from_client_id == client_id)
            var style = 'style="text-align:right"';
        $("#dialog").append('<div class="speech_item" '+ style +'> '+from_client_name+' <br> '+time+'<div style="clear:both;"></div><p class="triangle-isosceles top">'+content+'</p> </div>');
        if ($("#cscroll").attr("data-stat")*1) {
            scrdown("chat_lines")
        }
        //最长聊天纪录限制
        del_ttlist(50)
    }

    $(function(){
        select_client_id = 'all';
        $("#client_list").change(function(){
             select_client_id = $("#client_list option:selected").attr("value");
        });
    });
  </script>
<style type="text/css">
.chat-cont .chat-cls {
	position: absolute;
	top: 0;
	right: 20px;
	z-index: 100;
}

.c_gift_cont_height {
	
}

#chat_lines {
	position: relative;
	overflow-y: auto;
	overflow-x: hidden;
}

.chat_cls {
	font-family: "微软雅黑";
	height: 30px;
	position: absolute;
	right: 18px;
	top: 10px;
	width: 168px;
	z-index: 99;
}

.chat_cls a {
	text-decoration: none;
	padding: 0px 5px;
	display: block;
	float: left;
	margin-right: 10px;
	width: 60px;
	height: 22px;
	background: url(../images/clear_bj.png) #f6f6f6 no-repeat;
	border: 1px solid #e6e6e6;
	color: #545454;
	font-size: 12px;
	line-height: 22px;
}
</style>
</head>
<body onload="connect();">
    <div class="container">
        <div class="row clearfix">
            <div class="col-md-1 column"></div>
            <div class="col-md-6 column">
                <div class="thumbnail chat_cont">
                    <div class="c_cont clearfix chat_cont c_gift_cont_height">
                        <div class="chat_cls" id="chat_menu" style="display: none;">
                            <a class="scr" id="cscroll" href="javascript:;" data-stat="1">开始滚屏</a> <a title="清空" class="cle" href="javascript:;" onclick="ctrlclear('chat_line_list')">清屏</a>
                        </div>
                        <div class="c_cont clearfix" id="chat_lines" style="height: 500px;">
                            <div class="c_text overview">
                                <div class="viewport">
                                    <div class="chat_line">
                                        <div class="caption" id="dialog"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div id="chat" style="display:none;">
                    <form onsubmit="onSubmit(); return false;">
                        <select style="margin-bottom: 8px" id="client_list">
                            <option value="all">所有人</option>
                        </select>
                        <textarea class="textarea thumbnail" id="textarea"></textarea>
                        <div class="say-btn">
                            Ctrl + Enter 可发送 <input type="submit" class="btn btn-default" value="发表" />
                        </div>
                    </form>
                </div>
				<div id="guess">
					<form onsubmit="onGuess(); return false;">
                        <input type="text" value="" id="input_guess">
                        <div class="say-btn">
                            Ctrl + Enter 可发送 <input type="submit" class="btn btn-default" value="发表" />
                        </div>
                    </form>
				</div>
            </div>
            <div class="col-md-3 column">
                <div class="thumbnail">
                    <div class="caption" id="userlist"></div>
                </div>
            </div>
        </div>
    </div>
</body>
<script>
$(".chat_cont").bind("mouseover", function (c) {
  $("#chat_menu").show()
});
$(".chat_cont").bind("mouseleave", function (c) {
  $("#chat_menu").hide()
});
$("#cscroll").click(function () {
    var c = $(this).attr("data-stat")*1;
    $(this).removeClass("scr clo");
    if (!c) {
        $(this).html("开始滚屏");
        $(this).addClass("scr");
        $(this).attr("data-stat", 1)
    } else {
        $(this).html("关闭滚屏");
        $(this).addClass("clo");
        $(this).attr("data-stat", 0)
    }
    return false
});
function scrdown(c) {
    $("#" + c).scrollTop($("#" + c).prop("scrollHeight"))
}
function ctrlclear(d) {
    $("#dialog").html("");
    if ($("#cscroll").data("stat")*1) {
        scrdown("chat_lines")
    }
}
function del_ttlist(d) {
    var c = $(".speech_item").length;
    if (c >= d) {
        $(".speech_item").eq(0).remove()
    }
}
document.onkeydown=function(event){
    if(window.event.ctrlKey && window.event.keyCode==13){
        onSubmit();
    }
}

</script>
</html>
